package ci.web.util;

import java.net.URL;
import java.net.URLClassLoader;

/**
 * ClassLoader for ci
 * @author zhh
 */
public class CiClassLoader extends URLClassLoader {

    //package-prefix
    private final String prefix;
    /**
     * @param packagePrefix package-prefix
     */
    public CiClassLoader(String packagePrefix) {
        this(packagePrefix, new URL[0], null);
    }
    /**
     * @param packagePrefix package-prefix
     * @param parent        父ClassLoader
     */
    public CiClassLoader(String packagePrefix, ClassLoader parent) {
        this(packagePrefix, new URL[0], parent);
    }
    /**
     * @param packagePrefix package-prefix
     * @param urls          类路径
     * @param parent        父ClassLoader
     */
    public CiClassLoader(String packagePrefix, URL[] urls, ClassLoader parent) {
        super(urls, parent);
        this.prefix = packagePrefix;
    }
    /**
     * 添加类路径
     * @param url
     */
    public void addPath(URL url) {
        this.addURL(url);
    }
    /**
     * 重写loadClass<br/>
     * 1.判断是否加载过，加载过直接返回<br/>
     * 2.判断是否是允许加载的脚本，是则调用自身直接加载，不是则调用父类加载器/系统加载器进行加载
     * @param name
     * @param resolve
     * @return 加载到的类
     */
    @Override
    public Class<?> loadClass(String name, boolean resolve)
            throws ClassNotFoundException {
        if(name.startsWith(prefix)==false){
            return super.loadClass(name, resolve);
        }
        Class<?> clazz = null;
        clazz = super.findLoadedClass(name);
        if (clazz == null) {
            clazz = findClass(name);
        }
        if (resolve) {
            resolveClass(clazz);
        }
        return clazz;
    }

}
